package com.example.photograph.shiro.service;

import com.example.photograph.constant.ShiroConstants;
import com.example.photograph.domain.SysUser;
import com.example.photograph.exception.user.CaptchaException;
import com.example.photograph.exception.user.UserNotExistsException;
import com.example.photograph.service.ISysUserService;
import com.example.photograph.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 登录校验方法
 * 
 * @author wuyj
 */
@Component
public class SysLoginService
{
    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private ISysUserService userService;

    /**
     * 登录
     */
    public SysUser login(String username, String password)
    {
        // 验证码校验
        if (!StringUtils.isEmpty(ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA)))
        {
            throw new CaptchaException();
        }
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            throw new UserNotExistsException();
        }
        // 查询用户信息
        SysUser user = userService.selectUserByLoginName(username);
        if (user == null)
        {
            throw new UserNotExistsException();
        }
        passwordService.validate(user, password);
        return user;
    }
}
